import utils from '../utils'
import {Bounds} from '../utils'
import Common from '../common.js'
import Dataset from './index.js'
import paths from '../paths'

// Split into datasets with one layer each
function splitDataset(dataset) {
  return dataset.layers.map(lyr => {
    const split = {
      arcs: dataset.arcs,
      layers: [lyr],
      info: dataset.info
    }
    paths.dissolveArcs(split) // replace arcs with filtered + dissolved copy
    return split
  })
}
// clone coordinate data, shallow-copy attribute data
function copyDatasetForExport(dataset) {
  const d2 = utils.extend({}, dataset)
  d2.layers = d2.layers.map(Dataset.copyLayerShapes)
  if (d2.arcs) {
    d2.arcs = d2.arcs.getFilteredCopy()
  }
  return d2
}
// shallow-copy layers, so they can be renamed (for export)
function copyDatasetForRenaming(dataset) {
  return utils.defaults({
    layers: dataset.layers.map(function(lyr) {return utils.extend({}, lyr)})
  }, dataset)
}
function getDatasetBounds(dataset) {
  const bounds = new Bounds()
  dataset.layers.forEach((lyr) => {
    const lyrbb = Dataset.getLayerBounds(lyr, dataset.arcs)
    if (lyrbb) bounds.mergeBounds(lyrbb)
  })
  return bounds
}
function datasetHasGeometry(dataset) {
  return utils.some(dataset.layers, function(lyr) {
    return Common.layerHasGeometry(lyr)
  })
}
function datasetHasPaths(dataset) {
  return utils.some(dataset.layers, function(lyr) {
    return Common.layerHasPaths(lyr)
  })
}
// Transform the points in a dataset in-place; don't clean up corrupted shapes
function transformPoints(dataset, f) {
  if (dataset.arcs) {
    dataset.arcs.transformPoints(f)
  }
  dataset.layers.forEach((lyr) => {
    if (Common.layerHasPoints(lyr)) {
      utils.transformPointsInLayer(lyr, f)
    }
  })
}
export default {
  datasetHasGeometry,
  datasetHasPaths,
  splitDataset,
  copyDatasetForRenaming,
  copyDatasetForExport,
  getDatasetBounds,
  transformPoints,
}